'''
CSV
Comma-Separate Values
逗号分隔值
文档内容是由 ',' 号分隔的一列列的数据构成的。
CSV是文本格式，但是它能和 EXCEL互转
编辑方便、可视化效果好、轻量级数据存储
'''

import csv

'''Python3.x r w a r+
Python2.x rb wb r w a r
'''
# data = [['IG.wxz', '29'], ['Pony', '35'], ['Robin Lee', '36'], ['Jack Ma', 40], ['黄渤', '37']]
data = [('IG.wxz', '29'), ('Pony', '35'), ('Robin Lee', '36'), ('Jack Ma', 40), ('黄渤', '37')]

'''CSV 写操作 write'''
with open('example.csv', 'w', newline='', encoding='utf-8-sig') as f_csv:
    # .writer() 作用是创建CSV的写容器 相当于一个副本
    writer = csv.writer(f_csv)
    # .writerow() 写入数据 并且写入数据之后自动换行，行数+1
    writer.writerow(['name', 'age'])
    # 迭代写入数据
    '''按1行写入数据'''
    # for row in data:
    #     writer.writerow(row)
    '''多行写入数据'''
    writer.writerows(data)

'''CSV 读操作  read'''
import os
file_name = os.path.join(os.getcwd(), 'example.csv')
if os.path.exists(file_name):
    with open(file_name, 'r', encoding='utf-8-sig') as f_csv:
        reader = csv.reader(f_csv)
        print(type(reader))
        next(reader)
        for row in reader:
            # .line_num 表示记录的行 读完之后会自动+1
            print(reader.line_num, row)
            print(row[0], row[1])

'''字典的数据 存储'''
dict_data = [
    {'name': '张三', 'age': 18},
    {'name': '张三1', 'age': 19},
    {'name': '张三2', 'age': 20},
    {'name': '张三3', 'age': 21},
]

with open('example01.csv', 'w', newline='', encoding='utf-8-sig') as f_csv:
    f_name = ['name', 'age']
    writer = csv.DictWriter(f_csv, fieldnames=f_name)
    writer.writeheader()
    # writer.writerows(dict_data)
    for row in dict_data:
        writer.writerow(row)

with open('example01.csv', 'r', encoding='utf-8-sig') as f_csv:
    reader = csv.DictReader(f_csv)
    print(reader.line_num)
    # next(reader)
    for row in reader:
        print(row) #{'name': '张三', 'age': 18},
        print(reader.line_num, row['name'], row['age'])
